<?php
declare (strict_types = 1);

namespace app\common\middleware\http;

use adminmatrix\server\app\server\JsonService;
use app\adminapi\service\AdminTokenService;
use app\common\cache\AdminTokenCache;
use think\exception\HttpException;
use think\facade\Config;

class LoginMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('token');
//        $isNotNeedLogin = $request->controllerObject->isNotNeedLogin();
        if (empty($token) && !$request->isNeedLogin)
            return throw new HttpException(403  , '请求缺少token');


        $adminInfo = ( new AdminTokenCache()) -> getAdminInfo($token);

        if (empty($adminInfo) && !$request->isNeedLogin)
            return throw new HttpException(401 , '登录超时,请重新登陆');


        if ($adminInfo)
        {
            $beExpireDuration = Config::get('adminmatrix.admin_token.be_expire_duration');
            if (time() > ($adminInfo['expire_time'] - $beExpireDuration))
            {
                $reslut = AdminTokenService::overtimeToken($token);
                if (empty($reslut))
                    return throw new HttpException(401 , '登录过期');
            }
        }


        $request->adminInfo = $adminInfo;
        $request->adminId   = $adminInfo['admin_id'] ?? 0;
        return  $next($request);
    }
}
